<template>
  <div class="add-site-wrap" ref="container" :style="style">
    <div class="steps-main" v-if="isEdit !== true">
      <el-steps :space="300" :active="active" :center="true" :align-center="true">
        <el-step title="1.填写企业ID"></el-step>
        <el-step title="2.完善企业基本信息"></el-step>
        <el-step title="3.开户成功"></el-step>
      </el-steps>
    </div>
    <el-form ref="form" :model="form" label-width="150px" :rules="rules" class="add-site-form" :class="{'left': !isEdit}">

      <!-- 第一步钉钉信息 start -->
      <div class="form-section" v-if="active === 1 || isEdit === true">
        <el-form-item label="企业CorpID：" prop="corp_id">
          <el-input v-model="form.corp_id"></el-input>
        </el-form-item>
        <el-form-item label="企业CorpSecret：" prop="corp_secret">
          <el-input v-model="form.corp_secret"></el-input>
        </el-form-item>
        <el-form-item label="应用AgentID：" prop="agent_id">
          <el-input v-model="form.agent_id"></el-input>
        </el-form-item>
      </div>
      <!-- 第一步钉钉信息 end -->

      <!-- 第二步输入企业相关信息 start -->
      <div class="form-section" v-if="active === 2 || isEdit === true">
        <el-form-item label="企业名称" prop="company_name">
          <el-input v-model="form.company_name" :value="form.company_name"></el-input>
        </el-form-item>
        <el-form-item label="企业简介" prop="introduction">
          <el-input type="textarea" v-model="form.introduction"></el-input>
        </el-form-item>
        <!-- <el-form-item label="所在地" prop="address">
          <region-picker v-model="address" :data="regions"></region-picker>
        </el-form-item> -->
        <el-form-item label="企业logo" prop="company_logo">
          <QiniuUpload v-model="form.company_logo" :value="form.company_logo" :defaultImage="form.logo"></QiniuUpload>
        </el-form-item>
        <el-form-item label="站点名称" prop="site_name">
          <el-input v-model="form.site_name"></el-input>
        </el-form-item>
        <template v-if="this.isEdit !== true">
          <el-form-item label="联系人姓名" prop="nickname">
            <el-input v-model="form.nickname"></el-input>
          </el-form-item>
          <el-form-item label="联系人手机" prop="mobile">
            <el-input v-model="form.mobile"></el-input>
          </el-form-item>
          <el-form-item label="联系人邮箱" prop="email">
            <el-input v-model="form.email"></el-input>
          </el-form-item>
          <el-form-item label="管理密码" prop="password">
            <el-input type="password" v-model="form.password"></el-input>
          </el-form-item>
          <el-form-item label="确认管理密码" prop="confirmPassword">
            <el-input type="password" v-model="form.confirmPassword"></el-input>
          </el-form-item>
        </template>
        <el-form-item v-if="this.isEdit" label="应用链接:">
           <span class="copy-link">{{ 'http://scrm.91mycloud.com/scrm/index.html?dd_nav_bgcolor=FF01AAEF&t=' + Math.ceil(Math.random() * 100000)  + '&site_id=' + form.id }}</span>
        </el-form-item>
      </div>
      <!-- 第二步输入企业相关信息 end -->

      <!-- 第三步完成开户 start -->
      <div v-if="active === 3 && isEdit !== true">
        <div class="success-tip">恭喜您，新企业开户成功！</div>
      </div>
      <!-- 第三步完成开户 end -->

      <!-- 步骤控制按钮 start -->
      <div class="form-group" :class="{'left': isEdit, 'right': isEdit !== true}">
        <el-button class="prev-step-btn" v-if="active === 2" @click="active=1">返回上一步</el-button>
        <el-button class="next-step-btn" v-if="active < 3 && isEdit !== true" @click="nextStep">下一步</el-button>
        <el-button type="primary" class="save-btn" v-if="isEdit === true" @click="submit()">保存</el-button>
      </div>
      <!-- 步骤控制按钮 end -->
    </el-form>
  </div>
</template>
<style lang="scss">
.steps-main {
  // text-align: center;
}

.form-section {
  width: 70%;
}

.left {
  .form-section {
    width: 70%;
    margin-left:60px;
  }
}

.success-tip {
  font-size: 16px;
  text-align: center;
  font-weight: bolder;
  color: #20a0ff;
}

.copy-link {
  white-space: nowrap;
  // max-width: 93%;
  // text-overflow: ellipsis;
  // overflow: hidden;
}

.form-group.right {
  float: right;
  margin-right: 20px;
}

.form-group.left {
  margin-left: 130px;
}

.next-step-btn {

}

.add-site-form {
  max-width: 1100px;
  margin: 40px auto 0;
  padding-bottom:20px;
  overflow: hidden;
}

</style>
<script>
  import { Steps, Step, Form, FormItem, Input, Button } from 'element-ui'
  import { number, phone, email } from '../validators'
  import { mapActions } from 'vuex'
  import RegionPicker from 'region-picker'
  import QiniuUpload from '../components/QiniuUpload'
  import data from 'region-picker/src/components/data.json'
  import N from '../lib/notification'
  import Q from 'q'

  export default {
    props: ['isEdit'],
    components: {
      [Steps.name]: Steps,
      [Step.name]: Step,
      [Form.name]: Form,
      [FormItem.name]: FormItem,
      [Input.name]: Input,
      [Button.name]: Button,
      [RegionPicker.name]: RegionPicker,
      QiniuUpload
    },
    methods: {
      validateForm (formName) {
        return Q.Promise((resolve, reject) => {
          this.$refs[formName]
          .validate((valid) => {
            if (valid) {
              resolve(true)
            } else {
              reject(false)
            }
          })
        })
      },
      nextStep () {
        this.validateForm('form')
        .then((valid) => {
          if (this.active === 2) {
            setTimeout(() => {
              this.submit()
            }, 1000)
          } else {
            this.active ++
          }
        })
      },
      submit () {
        return this.saveSite(this.form)
        .then((response) => {
          if (response.data.errcode === 0) {
            if (this.isEdit === true) {
              N.notify('success', '保存成功!')
            } else {
              this.active++
              N.notify('success', '企业开户成功!')
            }
          } else {
            N.notify('error', response.data.errmsg)
          }
        }).catch((error) => {
          N.notify('error', '后台出了点小问题喔！请联系管理员!')
          console.log(error)
        })
      },
      ...mapActions({
        'saveSite': 'saveSite',
        'getSite': 'getSite'
      })
    },
    mounted () {
      if (this.isEdit === true) {
        this.siteId = this.$route.params['id']
        this.getSite(this.$route.params).then((response) => {
          if (response.data.errcode === 0) {
            this.form = response.data.results
            this.form['company_logo'] = this.form.logo
          }
        })
      }

      const windowHeight = window.innerHeight
      const offsetTop = this.$refs['container'].offsetTop
      this.tabHeight = windowHeight - offsetTop
      if (this.isEdit !== true) {
        this.style = 'height:' + this.tabHeight + 'px; overflow-y: auto;'
      } else {
        this.style = ''
      }
    },
    data () {
      return {
        active: 1,
        siteId: null,
        form: {
          'agent_id': null,
          'company_name': null,
          'introduction': null
        },
        style: '',
        tabHeight: 700,
        regions: data,
        rules: {
          'corp_id': [
            { required: true, message: '请输入企业CorpID' }
          ],
          'corp_secret': [
            { required: true, message: '请输入企业CorpSecret' }
          ],
          'company_name': [
            { required: true, message: '请输入企业名称', trigger: 'blur' }
          ],
          'introduction': [
            { required: true, message: '请输入公司简介', trigger: 'blur' }
          ],
          'nickname': [
            { required: true, message: '请输入联系人姓名', trigger: 'blur' }
          ],
          'password': [
            { required: true, message: '请输入登录密码', trigger: 'blur' }
          ],
          'company_logo': [
            { required: true, message: '请上传企业logo' }
          ],
          'site_name': [
            { required: true, message: '请输入站点名称', trigger: 'blur' }
          ],
          'agent_id': [
            { required: true, message: '请输入应用AgentID', trigger: 'blur' },
            { validator: number, message: '应用AgentID应为数字' }
          ],
          'mobile': [
            { required: true, message: '请输入联系人手机', trigger: 'blur' },
            { validator: phone, message: '联系人手机格式不正确' }
          ],
          'email': [
            { required: true, message: '请输入联系人邮箱', trigger: 'blur' },
            { validator: email, message: '联系人邮箱格式不正确' }
          ],
          'confirmPassword': [
            { required: true, message: '请确认管理密码' },
            {
              validator: (rule, value, callback) => {
                if ((this.form.password === this.form.confirmPassword) === false) {
                  callback(new Error(rule.message))
                } else {
                  callback()
                }
              },
              message: '两次输入的管理密码不一致'
            }
          ]
        }
      }
    }
  }
</script>
